package org.mech.sefer.client.ui.task.listener;

import org.apache.pivot.util.concurrent.Task;
import org.apache.pivot.util.concurrent.TaskListener;
import org.apache.pivot.wtk.TaskAdapter;
import org.mech.sefer.client.ui.task.callback.TaskCallback;

public class DefaultTaskListener<T> implements TaskListener<T> {

	private TaskAdapter<T> adapter;

	public DefaultTaskListener(TaskCallback<T> callback) {
		adapter = new TaskAdapter<T>(new ListenerCallbackAdapter<T>(callback));
	}

	@Override
	public void executeFailed(Task<T> task) {
		adapter.executeFailed(task);
	}

	@Override
	public void taskExecuted(Task<T> task) {
		adapter.taskExecuted(task);
	}

	private static class ListenerCallbackAdapter<V> implements TaskListener<V> {

		private TaskCallback<V> callback;

		public ListenerCallbackAdapter(TaskCallback<V> callback) {
			this.callback = callback;
		}

		@Override
		public void executeFailed(Task<V> task) {
			callback.onFailed(task.getFault());
		}

		@Override
		public void taskExecuted(Task<V> task) {
			callback.onSuccess(task.getResult());
		}

	}

}
